package com.heima.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.heima.pojo.User;
import com.heima.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    //资源名称
    public static final String RESOURCE_NAME_QUERY_USER_BY_NAME = "queryUserByUserName";

    //value是资源名称，是必填项。blockHandler填限流处理的方法名称
    @Override
    @SentinelResource(value = RESOURCE_NAME_QUERY_USER_BY_NAME,
            blockHandler = "queryUserByUserNameBlock",
            fallback = "queryUserByUserNameFallBack")
    public User queryByUserName(String userName) {
        if (userName == null || "error".equals(userName)) {
            //抛出异常
            throw new RuntimeException("queryByUserName() command failed, userName is null");
        }
        return new User("0", userName, 18);
    }

    //注意细节，一定要跟原函数的返回值和形参一致，并且形参最后要加个BlockException参数
    //否则会报错，FlowException: null
    public User queryUserByUserNameBlock(String userName, BlockException ex) {
        //打印异常
        ex.printStackTrace();
        return new User("xxx", "用户名称：{" + userName + "},资源访问被限流", 0);
    }
    //熔断之后的方法
    public User queryUserByUserNameFallBack(String userName, Throwable ex) {
        //打印日志
        ex.printStackTrace();
        return new User("-1", "用户名称：{" + userName + "},系统异常，请稍后重试", 0);
    }

}